<?php
include_once('./config/config.php');

$action = isset($_GET['action']) ? $_GET['action'] : '';

//退出登录，清空管理员身份
if($action == 'logout') {
    // 清空session
    setcookie('admin','',time()-1);
    setcookie('id','',time()-1);
    // 页面跳转
    ShowMsg('退出成功', './login.php');
    exit;
}
    // 判断是否是post提交
    if ($_POST) {
        /**
         * 处理登录逻辑
         * 
         * isset() 用于检查变量是否已经声明并且值不为NULL
         */
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $code = isset($_POST['code']) ? $_POST['code'] : '';

        if (strtolower($code) != $_SESSION['code']){
            // var_dump(strtolower($code));
            ShowMsg('验证码错误');
            exit;
        }

        $sql = "SELECT * FROM `per_admin` WHERE `username` = '$username'";

        $admin = find($sql);

        if(!$admin) {
            ShowMsg('用户名或密码错误');
            exit;
        }

        // 判断密码 加密之后干掉
        // $salt = build_randstr();
        
        //密码加密
        $password = md5($password . $admin['salt']);

        // 密码比对
        if($password != $admin['password']) {
            ShowMsg('密码错误');
            exit;
        }

        // 将用户名和密码写入cookie 存储管理员信息
        setcookie('id',$admin['id']);
        setcookie("username",$admin['username']);
        // setcookie('admin_id',$admin['id'],time()+3600);

        // 登录成功
        // 1. 记录登录状态
        $_SESSION['admin'] = $admin;

        // 2. 页面跳转
        header('Location:index.php');
        exit;
    }
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <?php
        include_once('common/meta.php');
    ?>
  </head>


  <body> 
    
    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="javascript:void(0)"><span class="second">Admin</span></a>
        </div>
    </div>

    <div class="row-fluid">
        <div class="dialog">
            <div class="block">
                <p class="block-heading">登录</p>
                <div class="block-body">
                    <form  method="post">
                        <label>用户名</label>
                        <input type="text" class="span12" name="username" placeholder="请输入用户名" required value="admin">
                        <label>密码</label>
                        <input type="password" class="span12" name="password" placeholder="请输入密码" required value="root">
                        <label>验证码</label>
                        <input type="text" class="span12" name="code" placeholder="请输入验证码" required>
                        <label for=""></label>
                        <img src="imgcode.php" alt="" onclick="this.src = 'imgcode.php'">
                        <button type="submit"  class="btn btn-primary pull-right">登录</button>
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
  </body>
</html>


